var FG;
if (!FG)
    FG = {};

FG.PopLayer = function(opts) {
    var this_ = this;
    
    this.moduleInfo = {
        name: 'poplayer',
        zhName: '弹出层',
        desc: '弹出层'
    };

    this.templates = {
        html: _.template('<iframe class="layer" src="<%= url %>" seamless="seamless"></iframe>'),
        image: _.template('<div class="layer" style="background-image: url(<%= url %>); <%= extraStyle %>"><span class="caption"><%= caption %></span></div>')
    };

    this.app = opts.app;
    this.target = opts.target;
    
    this.initView();
    this.hide();
};

FG.PopLayer.prototype.initView = function() {
    var this_ = this;
    this.$el = $(this.target);
    this.$content = $('<div class="content"></div>');
    this.$el.append(this.$content);
    this.$el.unbind().click(function(e) {
        e.stopPropagation();
        this_.hide();
    })
};

FG.PopLayer.prototype.loadSysPopLayers = function() {
    var layerList = FG.getSetting('poplayers', []);
    var activeLayerList = [],
        userTokens = FG.getUserStatus('poplayer_tokens', []),
        usedUserTokens = [];
    
    _.each(layerList, function(l) {
        if (!!l.token) {
            usedUserTokens.push(l.token);
            if (_.contains(userTokens, l.token)) {
                activeLayerList.push(l);
            }
        } else {
            activeLayerList.push(l);
        }
    });
    return activeLayerList;
};

FG.PopLayer.prototype.load = function(layer) {
    var this_ = this;
    if (_.isArray(layer)) {
        _.each(layer, function(l) {
            this_._loadOne(l);   // TODO: 如何逐个展示?
        }) 
    } else {
        this._loadOne(layer);
    }
};

FG.PopLayer.prototype._loadOne = function(layer) {
    var this_ = this;
    this.$content.empty();
    
    var $layer;
    if (layer.url.endsWith('.html') || layer.url.endsWith('.htm') || layer.type === 'html') {
        $layer = $(this.templates.html(layer));
        this.$content.append($layer);
        $layer.on("load", function(){
            $layer.contents().click(function(e) {
                this_.hide();
            })
        });
    } else if (
        layer.url.endsWith('.png') ||
        layer.url.endsWith('.gif') || 
        layer.url.endsWith('.jpg') || 
        layer.url.endsWith('.jpeg') ||
        layer.url.endsWith('.svg') ||
        layer.type === 'image'
    ) {
        var ctx = _.extend({caption: '', extraStyle: ''}, layer);
        if (!!layer.fullscreen) {
            ctx.extraStyle = 'background-size: 100% 100%';
        }
        $layer = $(this.templates.image(ctx));
        this.$content.append($layer)
    }
        
    this.$content.unbind().click(function(e) {
        e.stopPropagation();
        this_.hide();
    });
    if (!!layer.token) { FG.sendActivity({type: "remove_poplayer_tokens", tokens: [layer.token]}); }
};

FG.PopLayer.prototype.show = function() {
    this.$el.show();
};



FG.PopLayer.prototype.hide = function() {
    this.$el.hide();
};